<template>
  <div id="userInfoPage">
    <div style="width: 560px; margin-top: 16px">
      <a-form
        :model="formData"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        autocomplete="off"
        @finish="doUpdate"
      >
        <a-form-item label="用户名" name="userAccount">
          <a-input :value="formData.userAccount" disabled />
        </a-form-item>
        <a-form-item label="身份" name="userRole">
          <a-input :value="userRoleDict[formData.userRole]" disabled />
        </a-form-item>
        <a-form-item label="昵称" name="userName">
          <a-input v-model:value="formData.userName" :disabled="formData.userRole !== 'admin'" />
        </a-form-item>
        <a-form-item label="简介" name="userProfile">
          <a-textarea v-model:value="formData.userProfile" />
        </a-form-item>
        <a-form-item label="头像" name="userAvatar">
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :custom-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <img
              v-if="formData?.userAvatar"
              :src="formData?.userAvatar"
              alt="avatar"
              style="width: 70px; height: 70px"
            />
            <div v-else>
              <PlusOutlined v-if="loading" />
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">点击或拖拽上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { uploadImageUsingPost } from '@/api/fileUploadController.ts'
import { message, type UploadProps } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { editUserUsingPost } from '@/api/userController.ts'

const loginUserStore = useLoginUserStore()

const userRoleDict = {
  admin: '管理员',
  teacher: '教师',
  student: '学生',
}

const formData = reactive<API.UserVO>({
  id: loginUserStore.loginUser.id,
  userAccount: loginUserStore.loginUser.userAccount,
  userName: loginUserStore.loginUser.userName,
  userProfile: loginUserStore.loginUser.userProfile,
  userAvatar: loginUserStore.loginUser.userAvatar,
  userRole: loginUserStore.loginUser.userRole,
})

const doUpdate = async () => {
  const res = await editUserUsingPost({
    ...formData,
  })
  if (res.data.code === 0) {
    loginUserStore.fetchLoginUser()
    message.success('更新成功')
  } else {
    message.error('更新失败，' + res.data.message)
  }
}

const loading = ref<boolean>(false)

/**
 * 上传图片
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const res = await uploadImageUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      formData.userAvatar = res.data.data
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    console.log('图片上传失败，' + error)
    message.error('图片上传失败，' + error)
  }
  loading.value = false
}

/**
 * 上传前的校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传超过 2M 的图片')
  }
  return isJpgOrPng && isLt2M
}
</script>

<style scoped>
#userInfoPage {
  display: flex;
  justify-content: center;
}
</style>
